<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input 
        v-model="listQuery.filters.title" 
        placeholder="名称" 
        style="width: 200px;" 
        class="filter-item"/>
      <el-select 
        v-model="listQuery.filters.categoryId" 
        placeholder="分类名" 
        clearable 
        style="width: 120px" 
        class="filter-item">
        <el-option 
          v-for="item in CategoryList" 
          :value="item.id" 
          :label="item.title"/>
      </el-select>
      <el-button 
        class="filter-item" 
        type="primary" 
        icon="el-icon-search" 
        @click="handleFilter">{{ $t('all.search') }}</el-button>
      <el-button 
        class="filter-item" 
        style="margin-left: 10px;" 
        type="primary" 
        icon="el-icon-edit" 
        @click="handleCreate">{{ $t('all.add') }}</el-button>
    </div>
    <el-table
      v-loading="listLoading"
      :key="tableKey"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
    >
      <el-table-column 
        label="广告id" 
        prop="id" 
        align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="名称" 
        align="center">
        <template slot-scope="scope">
          <span>{{ scope.row.title }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        label="分类名" 
        align="center">
        <template slot-scope="scope">
          <span>{{ statusFilter(scope.row.categoryId) }}</span>
        </template>
      </el-table-column>
      <el-table-column 
        :label="$t('all.actions')" 
        align="center" 
        class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button 
            type="primary" 
            size="mini" 
            @click="handleUpdate(scope.row)">{{ $t('all.edit') }}</el-button>
          <el-button 
            size="mini" 
            type="danger" 
            @click="handleModifyStatus(scope.row)">{{ $t('all.del') }}
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination 
      v-show="total>0" 
      :total="total" 
      :page.sync="listQuery.page" 
      :limit.sync="listQuery.pageSize" 
      @pagination="getList" />

    <el-dialog 
      :title="dialogStatus" 
      :visible.sync="dialogFormVisible">
      <el-form 
        ref="Form" 
        :rules="rules" 
        :model="Form" 
        label-position="left" 
        label-width="70px" 
        style="width: 400px; margin-left:50px;">

        <el-form-item 
          label="所属分类" 
          prop="category">
          <el-select 
            v-model="Form.categoryId" 
            class="filter-item">
            <el-option 
              v-for="item in CategoryList" 
              :value="item.id" 
              :label="item.title"/>
          </el-select>
        </el-form-item>

        <el-form-item 
          label="名称" 
          prop="title">
          <el-input v-model="Form.title"/>
        </el-form-item>

        <el-form-item 
          label="图片" 
          prop="picurl">
          <Upload v-model="Form.picurl" />
        </el-form-item>

        <el-form-item 
          label="链接" 
          prop="url">
          <el-input 
            v-model="Form.url" 
            placeholder="请输入内容"/>
        </el-form-item>

        <el-form-item 
          label="排序" 
          prop="sort">
          <el-input v-model="Form.sort"/>
        </el-form-item>

      </el-form>

      <div 
        slot="footer" 
        class="dialog-footer">
        <el-button @click="dialogFormVisible = false">{{ $t('all.cancel') }}</el-button>
        <el-button 
          type="primary" 
          @click="dialogStatus==='创建'?createData():updateData()">{{ $t('all.confirm') }}</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { apibase, fetchList, remove, add, edit, getCategoryList } from '@/api/ad'
import Pagination from '@/components/Pagination' // Secondary package based on el-pagination

import Upload from '@/components/Upload/singleImage4'

export default {
  name: 'AdIndex',
  components: { Pagination,Upload},
  data() {
    return {

      imagecropperShow: false,
      imagecropperKey: 0,

      apibase: apibase,
      dialogFormVisible: false,
      dialogStatus: '',
      tableKey: 0,
      Form: {
        title: '',
        categoryId: '',
        picurl: 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191',
        sort: '',
        url: ''
      },
      CategoryList: [
        {
          id: '1111',
          title: '1111'
        }
      ],
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        pageSize: 20,
        order: 'desc',
        sort: 'id',
        filters: {
          title: '',
          categoryId: ''
        }
      },
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  created() {
    getCategoryList().then(response => {
      this.CategoryList = response.data
    })
    this.getList()
  },
  methods: {

    statusFilter(status) {
      var $res = ''
      this.CategoryList.forEach(function(item) {
        if (item.id == status) {
          $res = item.title
        }
      })
      return $res
    },
    resetForm() {
      this.Form = {
        title: '',
        categoryId: '',
        picurl: 'https://wpimg.wallstcn.com/577965b9-bb9e-4e02-9f0c-095b41417191',
        sort: '',
        url: ''
      }
    },
    getList() {
      this.listLoading = true
      fetchList(this.listQuery).then(response => {
        this.list = response.data.rows
        this.total = response.data.total

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.7 * 1000)
      })
    },
    handleFilter() {
      this.getList()
    },
    handleModifyStatus(row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        remove(row).then((res) => {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.handleFilter()
        })
      }).catch(() => {

      })
    },
    handleCreate() {
      this.resetForm()
      this.dialogStatus = '创建'
      this.dialogFormVisible = true
    },
    handleUpdate(row) {
      this.dialogStatus = '编辑'
      this.Form = Object.assign({}, row) // copy obj
      this.dialogFormVisible = true
    },
    createData: function() {
      this.$refs.Form.validate((valid) => {
        if (valid) {
          add(this.Form).then((res) => {
            if (res.data.code == 1) {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '创建成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              })
              return
            }
          }).catch((err) => {
            this.$message({
              showClose: true,
              message: '网络请求失败',
              type: 'error'
            })
            return false
          })
          this.dialogFormVisible = false
          this.handleFilter()
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 1)
          return false
        }
      })
    },
    updateData: function() {
      this.$refs.Form.validate((valid) => {
        if (valid) {
          edit(this.Form).then((res) => {
            if (res.data.code == 1) {
              this.dialogFormVisible = false
              this.$notify({
                title: '成功',
                message: '编辑成功',
                type: 'success',
                duration: 2000
              })
            } else {
              this.$notify.error({
                title: '错误',
                message: res.data.message
              })
              return false
            }
          }).catch((err) => {
            this.$message({
              showClose: true,
              message: '网络请求失败',
              type: 'error'
            })
            return false
          })
          this.dialogFormVisible = false
          this.handleFilter()
        } else {
          setTimeout(() => {
            var isError = document.getElementsByClassName('is-error')
            isError[0].querySelector('input').focus()
          }, 1)
          return false
        }
      })
    },
    cropSuccess(resData) {
      // console.log(resData);
      this.imagecropperShow = false
      this.imagecropperKey = this.imagecropperKey + 1
      this.Form.picurl = resData.data.url
    },
    close() {
      this.imagecropperShow = false
    }
  }
}
</script>

<style scoped>
  .avatar{
    width: 200px;
    height: 200px;
    border-radius: 50%;
  }
</style>
